package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Controller
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private CartService cartService;
    @Autowired
    private CatalogService catalogService;

    private int[] rightValidCode;

    //退出登录
    @GetMapping("/signout")
    public String signout(HttpSession session) {
        Account account = (Account) session.getAttribute("account");
        Cart cart = (Cart)session.getAttribute("cart");
        Order order = (Order)session.getAttribute("order");

        account = null;
        cart = null;
        order = null;

        session.setAttribute("account", account);
        session.setAttribute("cart",cart);
        session.setAttribute("order",order);

        return "catalog/main";
    }

    //跳转到登录页面
    @GetMapping("/signon")
    public String signon() {
        return "account/Signon";
    }

    //进行登陆验证
    @PostMapping("/login")
    public void login(String username, String password, String inputValidCode, Model model, HttpSession session, HttpServletResponse resp) throws IOException {
        PrintWriter pWriter = resp.getWriter();
        rightValidCode = (int[]) session.getAttribute("rightValidCode");
        Account account = accountService.getAccount(username, password);

        if (inputValidCode.length() != 4) {
            //验证码格式不通过
            pWriter.print("wrong valid code");
        } else {
            //验证码格式通过
            int inputValidCode1 = inputValidCode.charAt(0) - 48;
            int inputValidCode2 = inputValidCode.charAt(1) - 48;
            int inputValidCode3 = inputValidCode.charAt(2) - 48;
            int inputValidCode4 = inputValidCode.charAt(3) - 48;


            if ((inputValidCode1 != rightValidCode[0]) || (inputValidCode2 != rightValidCode[1]) ||
                    (inputValidCode3 != rightValidCode[2]) || (inputValidCode4 != rightValidCode[3])) {
                //验证码内容不提供
                pWriter.print("wrong valid code");
            } else if (account == null) {
                //密码错误
                pWriter.print("wrong password");
            } else {
                //密码正确
                if(accountService.isAdministrator(username)){
                    //是管理员
                    //操作管理员账户初始化
                    //账户信息和购物车信息加入session
                    session.setAttribute("isAdministrator", true);
                    session.setAttribute("account", account);

                    pWriter.print("administrator");
                    pWriter.flush();
                    pWriter.close();
                }
                else{
                    //是普通用户
                    if(account.getStatus().equals("NO")){
                        //用户权限被禁用
                        account = null;
                        pWriter.print("banned");
                    }
                    else {
                        //用户权限正常
                        //购物车初始化加载
                        Cart cart = new Cart();
                        List<CartItem> cartItemList = cartService.getCartItemsFromDatabase(username);

                        for (CartItem cartItem : cartItemList
                        ) {
                            String itemId = cartItem.getItem().getItemId();

                            boolean isInStock = catalogService.isItemInStock(itemId);
                            Item item = catalogService.getItem(itemId);

                            int quantity = cartItem.getQuantity();
                            cart.addItemAndQuantity(item, isInStock, quantity);
                        }

                        //账户信息和购物车信息加入session
                        session.setAttribute("cart", cart);
                        session.setAttribute("account", account);

                        pWriter.print("right");
                        pWriter.flush();
                        pWriter.close();
                    }

                }
            }
        }

        pWriter.flush();
        pWriter.close();

    }

    //跳转到注册界面
    @GetMapping("/newAccount")
    public String newAccount() {
        return "account/NewAccount";
    }

    //注册界面的用户名验证
    @GetMapping("/usernameIsExist")
    public void usernameIsExist(String username, HttpServletResponse resp) throws IOException {
        PrintWriter pWriter = resp.getWriter();
        try {
            if (accountService.isAccountExist(username) == false) {
                pWriter.print("Not Exist");
            } else {
                pWriter.print("Exist");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        pWriter.flush();
        pWriter.close();
    }

    //注册验证
    @PostMapping("/register")
    public String register(HttpServletRequest req, Model model){
        Account account = new Account();
        String confirmPassword = null;//保存“确认密码”
        String msg = null;
        boolean valid = true;

        account.setUsername(req.getParameter("username"));
        account.setPassword(req.getParameter("password"));
        confirmPassword = req.getParameter("repeatedPassword");
        account.setFirstName(req.getParameter("firstName"));
        account.setLastName(req.getParameter("lastName"));
        account.setEmail(req.getParameter("email"));
        account.setPhone(req.getParameter("phone"));
        account.setAddress1(req.getParameter("address1"));
        account.setAddress2(req.getParameter("address2"));
        account.setCity(req.getParameter("city"));
        account.setState(req.getParameter("state"));
        account.setZip(req.getParameter("zip"));
        account.setCountry(req.getParameter("country"));
        account.setLanguagePreference(req.getParameter("languagePreference"));
        account.setFavouriteCategoryId(req.getParameter("favouriteCategoryId"));

        if(account.getUsername() == null ||account.getUsername().trim().equals("")){
            msg = "Username is necessary";
            valid = false;
        }
        if(account.getPassword() == null || account.getPassword().trim().equals("")){
            msg = "Password is necessary";
            valid = false;
        }
        if(confirmPassword == null || confirmPassword.trim().equals("")){
            msg = "ConfirmPassword is necessary";
            valid =  false;
        }
        if(!account.getPassword().equals(confirmPassword)){
            msg = "Passwords are not the same";
            valid = false;
        }

        if(valid){

            accountService.insertAccount(account);
            msg = "Successful! Please Use Your NewAccount to Sign in! ";
            model.addAttribute("msg",msg);
        }
        else{
            model.addAttribute("msg",msg);
        }

        return "catalog/main";
    }

    //查看账户信息
    @GetMapping("/viewAccount")
    public String viewAccount(){
        return "account/ViewAccount";
    }

    //保存账户信息修改
    @PostMapping("/updateAccountInfo")
    public String updateAccountInfo(HttpServletRequest req, Model model,HttpSession session) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");

        Account account = (Account) session.getAttribute("account");
        String confirmPassword;
        String accountMsg;


        account.setPassword(req.getParameter("password"));
        confirmPassword = req.getParameter("repeatedPassword");
        account.setFirstName(req.getParameter("firstName"));
        account.setLastName(req.getParameter("lastName"));
        account.setEmail(req.getParameter("email"));
        account.setPhone(req.getParameter("phone"));
        account.setAddress1(req.getParameter("address1"));
        account.setAddress2(req.getParameter("address2"));
        account.setCity(req.getParameter("city"));
        account.setState(req.getParameter("state"));
        account.setZip(req.getParameter("zip"));
        account.setCountry(req.getParameter("country"));
        account.setLanguagePreference(req.getParameter("languagePreference"));
        account.setFavouriteCategoryId(req.getParameter("favouriteCategoryId"));

        if(account.getUsername() == null ||account.getUsername().trim().equals("")){
            accountMsg = "Username is necessary";
            model.addAttribute("accountMsg",accountMsg);
        }
        if(account.getPassword() == null || account.getPassword().trim().equals("")){
            accountMsg = "Password is necessary";
            model.addAttribute("accountMsg",accountMsg);
        }
        if(confirmPassword == null || confirmPassword.trim().equals("")){
            accountMsg = "ConfirmPassword is necessary";
            model.addAttribute("accountMsg",accountMsg);
        }
        if(!account.getPassword().equals(confirmPassword)){
            accountMsg = "Passwords are not the same";
            model.addAttribute("accountMsg",accountMsg);
        }
        else{
            accountService.updateAccount(account);
            accountMsg = "Successful Update! ";
            model.addAttribute("accountMsg",accountMsg);
        }

        return "account/ViewAccount";
    }

}
